import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { List } from 'immutable';
import { Observable } from 'rxjs';
import { addTodo, cancelEditing, startEditing, stopEditing, toggleCompletion, updateEditing } from './shared/actions';
import { Todo } from './shared/models/todo';
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.scss' ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit {
  newTodoText
  todos$: Observable<List<Todo>>
  allCompleted$: Observable<boolean>

  constructor(private store$: Store<any>) {
    this.todos$ = store$.select('todos')
    this.allCompleted$ = this.todos$.map((todos: List<Todo>) => {
      return todos.every(todo => todo.completed)
    })
  }

  ngOnInit() {
  }

  addTodo() {
    this.store$.dispatch(addTodo(this.newTodoText))
    this.newTodoText = null
  }

  setAllTo(completed: boolean) {
    console.log('set all to', completed)
  }

  toggleCompletion(todo: Todo) {
    this.store$.dispatch(toggleCompletion(todo))
  }

  remove(todo: Todo) {
  }

  editTodo(todo: Todo) {
    this.store$.dispatch(startEditing(todo))
  }

  stopEditing(todo: Todo, value) {
    if (todo.editing) {
      console.log('stop editing', todo, todo.editing)
      this.store$.dispatch(stopEditing(todo, value))
    }
  }

  updateEditingTodo(todo: Todo, value: string) {
    console.log('update', todo, value)
    this.store$.dispatch(updateEditing(todo, value))
  }

  cancelEditingTodo(todo: Todo) {
    console.log('cancel', todo)
    this.store$.dispatch(cancelEditing(todo))
  }

  removeCompleted() {

  }

  trackById(todo) {
    return todo.id
  }
}
